package ar.uba.dc.cmovil.tripplanner.services;

import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by anton on 10/3/13.
 */
class WikipediaDescriptionTask extends AsyncTask<String, Void, String> {
    private static String requestUrl = "http://es.wikipedia.org/w/api.php?format=json&action=query&titles=${query}&prop=extracts&exintro=1&explaintext=1&exchars=400";
    private static String queryPattern = "${query}";
    private HttpTaskHandler<String> taskHandler;

    private String getIntro(String query) throws IOException, JSONException {
        query = android.net.Uri.encode(query);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(new HttpGet(prepareRequestUrl(query)));
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null; ) {
            builder.append(line).append("\n");
        }

        JSONTokener tokener = new JSONTokener(builder.toString());
        JSONObject result = new JSONObject(tokener);

        JSONObject pages = result.getJSONObject("query").getJSONObject("pages");
        return pages.getJSONObject(pages.names().get(0).toString()).getString("extract");
    }

    private String prepareRequestUrl(String query) {
        return requestUrl.replace(queryPattern, query);
    }

    private void fail() {
        if (taskHandler != null) {
            taskHandler.onFail();
        }
    }

    public void setTaskHandler(HttpTaskHandler taskHandler) {
        this.taskHandler = taskHandler;
    }

    @Override
    protected void onPostExecute(String s) {
        if (taskHandler != null) {
            if (s == null) {
                fail();
            } else {
                taskHandler.onSuccess(s);
            }
        }
    }

    @Override
    protected String doInBackground(String... params) {
        String query = params[0];
        String result = "";
        try {
            result = getIntro(query);
            if (isRedirect(result)) {
                result = getIntro(newQueryFromRedirect(result));
            }
        } catch (IOException e) {
            e.printStackTrace();
            fail();
        } catch (JSONException e) {
            e.printStackTrace();
            fail();
        }

        return result;
    }

    private String newQueryFromRedirect(String result) {
        assert isRedirect(result);
        String[] split = result.split(" ");
        return split[1];
    }

    private boolean isRedirect(String result) {
        String[] split = result.split(" ");
        return split.length == 2 && split[0].toLowerCase().equals("redirect");
    }
}
